package org.example.erpapispringweb;


import org.example.erpapispringweb.config.ApiUserConfig;
import org.example.erpapispringweb.security.ApiUser;
import org.example.erpapispringweb.security.Token;
import org.example.erpapispringweb.security.TokenException;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Optional;
import java.util.UUID;

@Component
public class TokenServiceImpl implements TokenService {
    final RedisTemplate redisTemplate;
    final ApiUserConfig apiUserConfig;

    public TokenServiceImpl(RedisTemplate redisTemplate, ApiUserConfig apiUserConfig) {
        this.redisTemplate = redisTemplate;
        this.apiUserConfig = apiUserConfig;
    }

    private boolean isValidUser(ApiUser apiUser){
        return apiUser!=null && apiUserConfig.getUsers().stream()
                .anyMatch(u->u.getUsername().equals(apiUser.getUsername())&&u.getPassword().equals(apiUser.getPassword()));
    }
    @Override
    public Token createToken(ApiUser apiUser) throws TokenException {
        if (isValidUser(apiUser)){
            Token token = new Token(UUID.randomUUID().toString());
            redisTemplate.opsForValue().set(token.getAccessToken(),apiUser, Duration.ofSeconds(token.getExpiresIn()));
            return token;
        }
        throw new TokenException("用户名或密码错误");
    }

    @Override
    public Optional<ApiUser> getApiUser(String tokenValue) {
        if(tokenValue==null||tokenValue.isBlank()){
            return Optional.empty();
        }
        ApiUser apiUser = (ApiUser) redisTemplate.opsForValue().get(tokenValue);
        return Optional.ofNullable(apiUser);
    }
}
